package cn.huiyunche.driver.controller;

import cn.huiyunche.base.service.constant.TmsUrlConstant;
import cn.huiyunche.base.service.enums.TmsUrlTypeEnum;
import cn.huiyunche.base.service.interfaces.TmsQueueService;
import cn.huiyunche.base.service.interfaces.impl.TmsOrderCallHistoryServiceImpl;
import cn.huiyunche.base.service.model.TmsOrder;
import cn.huiyunche.base.service.vo.OrderDepartureVo;
import cn.huiyunche.base.service.vo.Result;
import cn.huiyunche.driver.service.OrderService;
import cn.huiyunche.driver.service.TmsImportService;
import cn.huiyunche.tools.basic.exceptions.BusinessException;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections4.map.HashedMap;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.formula.functions.T;
import org.joda.time.DateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 运单Controller
 *
 * @author lm
 */
@Controller
@RequestMapping("/wb")
public class DWaybillBackController {

    private static final Logger LOGGER = LoggerFactory.getLogger(DWaybillBackController.class);


    @Autowired
    private TmsImportService tmsImportService;

    @Autowired
    private OrderService orderService;

    @Autowired
    private TmsQueueService tmsQueueService = null;

    @Autowired
    private TmsOrderCallHistoryServiceImpl tmsOrderCallHistoryService;


    /**
     * import from excel test data
     *
     * @param key the id
     * @return the result
     */
    @RequestMapping(value = "/import", method = RequestMethod.POST)
    public
    @ResponseBody
    Result<T> testDataImport(@RequestParam("key") String key) {
        if (!StringUtils.equals(key, "driverTDI")) return null;

        Result<T> result = new Result<>(true, "导入订单");
        try {
            List<TmsOrder> tmsOrders = this.tmsImportService.importOrderExcel();
            LOGGER.info("testDataImport : {}", tmsOrders);
            if (CollectionUtils.isNotEmpty(tmsOrders)) {
                orderService.handleTmsOrders(tmsOrders);
            }
        } catch (Exception e) {
            LOGGER.error("testDataImport: error : {}", e);
            throw new BusinessException("确认回单失败");
        }
        return result;
    }

    /**
     * import from excel test data
     *
     * @param key the id
     * @return the result
     */
    @RequestMapping(value = "/fromTMS", method = RequestMethod.POST)
    public
    @ResponseBody
    Result<T> imFromTMS(String key, String lastTimeStr) {
        if (!StringUtils.equals(key, "driverTDI")) return null;

        Result<T> result = new Result<>(true, "导入订单");
        try {
            final String url = TmsUrlConstant.PULL_IMPORT;

            //查询上一次成功url调用成功的记录
            Date lastTime = tmsOrderCallHistoryService.getLastTimeSuccess(url, true);


            Map paramsMap = new HashedMap();
            if (StringUtils.isNotBlank(lastTimeStr)) {
                paramsMap.put("lastTime", lastTimeStr);
            } else {
                paramsMap.put("lastTime", new DateTime(lastTime).toString("yyyy-MM-dd HH:dd:ss:SSS"));
            }
            String resultStr = tmsOrderCallHistoryService.urlCall(url, TmsUrlTypeEnum.PULL_IMPORT.getValue(), paramsMap, 60000);
            LOGGER.info("DWaybillBackController.imFromTMS url return : {}", resultStr);
            if (StringUtils.isNotBlank(resultStr)) {
                JSONObject jsonObject = JSONObject.parseObject(resultStr);
                String data = jsonObject.get("data").toString();
                if (StringUtils.isNotBlank(data)) {
                    List<TmsOrder> tmsOrders = JSONArray.parseArray(data, TmsOrder.class);
                    LOGGER.info("saveTmsOrders tmsOrders : {}", tmsOrders);
                    orderService.handleTmsOrders(tmsOrders);
                }
            }
        } catch (Exception e) {
            LOGGER.error("testDataImport: error : {}", e);
            throw new BusinessException("导入订单失败");
        }
        return result;
    }


    @RequestMapping(value = "/shipedFromTMS", method = RequestMethod.POST)
    public
    @ResponseBody
    Result<T> departureFromTMS(String key, String lastTimeStr) {
        if (!StringUtils.equals(key, "driverTDI")) return null;

        Result<T> result = new Result<>(true, "获取发车时间");
        try {
            final String url = TmsUrlConstant.PULL_ORDER_DEPARTURE;
            //查询上一次成功url调用成功的记录
            Date lastTime = this.tmsOrderCallHistoryService.getLastTimeSuccess(url, true);
            Map paramsMap = new HashedMap();
            if (StringUtils.isNotBlank(lastTimeStr)) {
                paramsMap.put("lastTime", lastTimeStr);
            } else {
                paramsMap.put("lastTime", new DateTime(lastTime).toString("yyyy-MM-dd HH:dd:ss:SSS"));
            }

            String resultStr = this.tmsOrderCallHistoryService.urlCall(url, TmsUrlTypeEnum.PULL_ORDER_DEPARTURE.getValue(), paramsMap, 10000);
            LOGGER.info("zl departure order finish job result : {}.", result);
            if (StringUtils.isNotBlank(resultStr)) {
                JSONObject jsonObject = JSONObject.parseObject(resultStr);
                String data = jsonObject.getString("data");
                if (StringUtils.isNotBlank(data)) {
                    List<OrderDepartureVo> departureResults = JSONArray.parseArray(data, OrderDepartureVo.class);
                    if (org.apache.commons.collections4.CollectionUtils.isNotEmpty(departureResults)) {
                        orderService.orderDeparture(departureResults);
                    }
                }
            }


        } catch (Exception e) {
            LOGGER.error("testDataImport: error : {}", e);
            throw new BusinessException("获取发车失败");
        }
        return result;
    }


}
